#include "BlockQueue.hpp"
#include "Task.hpp"
#include <unistd.h>
#include <ctime>

int myAdd(int x,int y)
{
    return x+y;
}

void *consumer(void *args)
{
    BlockQueue<Task> *bqueue = (BlockQueue<Task> *)args;
    Task t;
    while (true)
    {
        bqueue->pop(&t);
        std::cout<<"消费："<<t.x_<<"+"<<t.y_<<"="<<t()<<std::endl;
        //sleep(1);
    }
    return nullptr;
}

void *producer(void *args)
{
    BlockQueue<Task> *bqueue = (BlockQueue<Task> *)args;
    int x = rand()%10 +1;
    usleep(rand()%1000);
    int y = rand()%5 +1;

    Task t(x,y,myAdd);
    while (true)
    {
        bqueue->push(t);
        std::cout<<"生产："<<t.x_<<"+"<<t.y_<<"= ?"<<std::endl;
        sleep(1);
    }
    return nullptr;
}

int main()
{
    srand((unsigned int)time(nullptr));
    BlockQueue<Task> *bqueue = new BlockQueue<Task>();

    pthread_t c[2],p[2];
    pthread_create(c,nullptr,consumer,(void*)bqueue);
    pthread_create(c+1,nullptr,consumer,(void*)bqueue);
    pthread_create(p,nullptr,producer,(void*)bqueue);
    pthread_create(p+1,nullptr,producer,(void*)bqueue);
    
    pthread_join(p[0],nullptr);
    pthread_join(p[1],nullptr);
    pthread_join(c[0],nullptr);
    pthread_join(c[1],nullptr);

    delete(bqueue);
    return 0;
}